<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <template #avatar>
        <MultiImageUpload
          v-model="formData.imgList1"
          :limit="1"
          @update:model-value="(val) => changeOneImg(val, formData, 'avatar')"
        />
      </template>
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
import { getDeptList, getOrganizationList, getUserList } from "@/commonData";
import { phoneRules } from "@/commonData/rules";
import { bankAccountTypeList, genderList, userTypeList } from "@/commonData/dict";
import { changeOneImg } from "@/utils/changeData";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const organizationList = ref([]);
const deptList = ref([]);
const roleList = ref([]);
const userList = ref([]);

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  // 1-姓名-必填-nickname
  // 2-手机号-正则-必填-mobile
  // 3-登录用户名-必填-username
  // 4-初始登录密码-password
  // 5、归属机构-orgId
  // 6、归属部门-deptId
  // 7、角色权限
  const list = [
    {
      requiredFlag: true,
      type: "tree-select",
      placeholder: "归属机构",
      prop: "orgId",
      label: "归属机构",
      attrs: {
        filterable: true,
        clearable: true,
        // data: mockTreeList,
        data: organizationList,
        // props: defaultProps,
        "check-strictly": true,
        // "node-key": "id",
      },
    },
    // {
    //   type: "select",
    //   placeholder: "归属部门",
    //   label: "归属部门",
    //   prop: "deptId",
    //   attrs: {
    //     filterable: true,
    //     clearable: true,
    //     style: {
    //       width: "100%",
    //     },
    //   },
    //   children: deptList,
    // },
    // {
    //   type: "select",
    //   placeholder: "用户",
    //   label: "用户",
    //   prop: "userID",
    //   attrs: {
    //     filterable: true,
    //     clearable: true,
    //     style: {
    //       width: "100%",
    //     },
    //   },
    //   children: userList,
    // },
    {
      type: "input",
      label: "姓名",
      prop: "name",
      placeholder: "姓名",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "手机号",
      prop: "phone",
      placeholder: "手机号",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
      rules: phoneRules,
    },
    {
      type: "input",
      label: "身份证号",
      prop: "idCardNo",
      placeholder: "身份证号",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "select",
      placeholder: "性别",
      label: "性别",
      prop: "gender",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: genderList,
    },
    {
      type: "select",
      placeholder: "银行账户类型",
      label: "银行账户类型",
      prop: "bankAccountType",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: bankAccountTypeList,
    },
    {
      type: "input",
      label: "账户名称",
      prop: "BankAccountName",
      placeholder: "账户名称",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "银行账号",
      prop: "BankName",
      placeholder: "银行账号",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "备注",
      prop: "remark",
      placeholder: "备注",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      slot: "avatar",
      label: "头像",
    },
  ];

  addProperty(list);
  return list;
};
requestFormOptions.value = createRequestFormOptions();

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();
  getOrganizationList(organizationList);
  getDeptList(deptList);
  getRoleList(roleList);
  getUserList(userList);
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await getUser(id);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await createUser(data);
      // ElMessage.success("操作成功");
    } else if (formType.value === "update") {
      await updateUser(data);
      // ElMessage.success("操作成功");
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const mockList = [
  { label: "模拟数据1", value: 1 },
  { label: "模拟数据2", value: 2 },
  { label: "模拟数据3", value: 3 },
  { label: "模拟数据4", value: 4 },
  { label: "模拟数据5", value: 5 },
];

const getFormData = () => {
  return formData.value;
};
</script>
